using UnityEngine;
using System.Collections;

public class ResetRotation : MonoBehaviour {
	public float rotationTime = 1;

	private bool reset, startReset, waitForRotation;
	private float angle, angleSum;
	private GameObject player, level;
	private Vector3 rotationAxis, playerPosition;

	// Use this for initialization
	void Start () {
		player = GameObject.Find("First Person Controller");
		level = GameObject.Find("Level");
	}

	// Update is called once per frame
	void Update () {
		if(waitForRotation) {
			waitForRotation = player.GetComponent<ChangeGravity>().changeCamera;
			player.transform.position = playerPosition;
			return;
		}

		if(startReset) {
			player.GetComponent<ChangeGravity>().rotationLocked = true;
			player.transform.position = playerPosition;
			// Set rotation axis
			rotationAxis = Vector3.Cross(level.transform.up, Vector3.up);
			if(rotationAxis == Vector3.zero)
				rotationAxis = level.transform.forward;
			
			rotationAxis.Normalize();
			//rotationStartTime = Time.time;
			angle = Vector3.Angle(level.transform.up, Vector3.up);

			reset = true;
			startReset = false;
			angleSum = 0;
		}

		if(reset) {
			player.transform.position = playerPosition;
			float angleStep = angle * (Time.deltaTime / rotationTime);
			if(angleSum + angleStep > angle) {
				angleStep = angle - angleSum;
			}
			angleSum += angleStep;
			level.transform.RotateAround(player.transform.position, rotationAxis, angleStep);
			if(angleSum >= angle) {
				player.GetComponent<ChangeGravity>().rotationLocked = false;
				player.GetComponent<CharacterMotor>().movement.velocity = Vector3.zero;
				reset = false;
			}
		}
	}
	
	void OnTriggerEnter(Collider c) {
		if(level.transform.up != Vector3.up) {
			waitForRotation = player.GetComponent<ChangeGravity>().changeCamera;
			startReset = true;
			playerPosition = player.transform.position;
		}
	}
	
	void OnTriggerExit(Collider c) {

	}
}
